package admin

import (
	"editor/constant"
	"editor/service/mdFile"
	"editor/store"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"net/http"
)

func AddFileHandler(c *gin.Context) {
	title := c.PostForm("title")
	if title == "" {
		c.JSON(http.StatusOK, constant.Response{Msg: "文件名为空或格式错误", Code: 1})
		return
	}

	categoryId := cast.ToInt64(c.PostForm("categoryId"))
	sortNum := cast.ToInt64(c.PostForm("sortNum"))

	isRepeat, err := mdFile.CheckTitleIsRepeat(c, title, categoryId, 0)
	if err != nil {
		store.Errorf(c, err, "title:%s,categoryId:%d", title, categoryId)
		c.JSON(http.StatusOK, constant.Response{Msg: "CheckTitleIsRepeat failed", Code: 3})
		return
	}
	if isRepeat {
		c.JSON(http.StatusOK, constant.Response{Msg: "title is repeat", Code: 4})
		return
	}
	defaultCons := `

[TOC]

[TOCM]

# ` + title + `.md

`

	id, err := mdFile.AddFile(c, title, categoryId, defaultCons, sortNum)
	if err != nil {
		store.Errorf(c, err, "AddFile failed title:%s,category:%d", title, categoryId)
		c.JSON(http.StatusOK, constant.Response{Msg: "add mdFile failed", Code: 5})
		return
	}

	c.JSON(http.StatusOK, constant.Response{Msg: "Success", Code: 0, Data: map[string]interface{}{"id": id}})
}
